package com.fenghongzhang.module_main.ui.post

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fenghongzhang.lib_core.exception.ApiException
import com.fenghongzhang.module_main.api.ApiService

class PostPageSource(
    private val category: Int? = null,
    private val topicId: String? = null,
    private val keyword: String? = null,
    private val vehicleModelId: String? = null,
    private val series: String? = null,
    private val memberId: String? = null,
    private val ifMy: Int? = null,
    private val ifFocus: Int? = null,
    private val ifCollection: Boolean? = null,
    private val topicCategory: Int? = null,
    private val apiService: ApiService,
    //总条数
    private val totalSizeListener: ((Int) -> Unit)? = null,
    private val module: Int = 1

) : PagingSource<Int, PostModel>() {
    override fun getRefreshKey(state: PagingState<Int, PostModel>): Int? {
        return 1
    }
     // 允许重复使用 key

    override val keyReuseSupported: Boolean
        get() = true
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PostModel> {
        val currentPage = params.key ?: 1
        val pageSize = params.loadSize

        val posts =  apiService.queryPostsByPage(
            category = category,
            topicId = topicId,
            vehicleModelId = vehicleModelId,
            series = series,
            content = keyword,
            memberId = memberId,
            ifMy = ifMy,
            ifFocus = ifFocus,
            topicCategory = topicCategory,
            currentPage,
            pageSize
        )
        if (posts.data == null) {
            return LoadResult.Error(ApiException.getApiException(posts.code, posts.msg))
        }

        return LoadResult.Page(
            data = posts.data!!.posts,
            prevKey = 2,
            nextKey = 3
        )
    }


}